#!/bin/bash
PID=0
DIR=`dirname $0`
PWDPATH=`cd $DIR && pwd`
PIDFILE=$PWDPATH/nohup.pid
OUTFILE=$PWDPATH/nohup.out
PROGNAME='trojan-manager'

cd $PWDPATH

run() {
    nohup $PWDPATH/lib/$PROGNAME >$OUTFILE 2>&1 & echo $!>$PIDFILE
}

init() {
    if [ -f $PIDFILE ]; then
        PID=`cat $PIDFILE`
    fi
}

check() {
  ProcNumber=`ps -ef | grep -w $PWDPATH/lib/$PROGNAME | grep -v grep|wc -l`
  if [ $ProcNumber -le 0 ];then
     return 0
  else
     return 1
  fi
}


start() {
    init
    check
    if [ $? -eq 1 ]; then
        echo "$PROGNAME is run!" && exit 1
    else
        run
        echo "Start $PROGNAME!" && exit 0
    fi
}

restart() {
    init
    check
    if [ $? -eq 1 ]; then
        kill $PID>/dev/null 2>&1
    fi
    run

    echo "Restart $PROGNAME!" && exit 0
}

stop() {
    init
    check
    if [ $? -eq 1 ]; then
      if [ $PID -gt 0 ]; then
        kill $PID>/dev/null 2>&1
      fi
      echo "$PROGNAME is stop!" && exit 0
    else
        echo "$PROGNAME is not run!" && exit 1
    fi
}

status() {
    init
    check
    if [ $? -eq 1 ]; then
        echo "$PROGNAME is run!" && exit 0
    else
        echo "$PROGNAME is not run!" && exit 1
    fi
}

clean() {
    if [ -f $OUTFILE ]; then
        rm -f $OUTFILE
    fi
    if [ -f $PIDFILE ]; then
        rm -f $PIDFILE
    fi
    echo 'Clean success!' && exit 0
}

case "$1" in
    start)
        $1
        exit 0
        ;;
    restart)
        $1
        exit 0
        ;;
    stop)
        $1
        exit 0
        ;;
    status)
        $1
        exit 0
        ;;
    clean)
        $1
        exit 0
        ;;
    *)
        echo $DIR
        echo 'Usage: {start|stop|restart|status|clean}'
        ;;
esac
